package paproject.httputil;

import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

@Component
public class HttpUtils {

    private PoolingHttpClientConnectionManager cm;

    public HttpUtils(){
        this.cm = new PoolingHttpClientConnectionManager();

        //设置连接数
        this.cm.setMaxTotal(100);

        //设置主机最大连接数
        this.cm.setDefaultMaxPerRoute(10);
    }

    public String doGetHtml(String url){
        //1.不是每次创建新的HttpClient,而是从连接池中获取HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(this.cm).build();
        //2.创建HttpGet对象，设置url访问地址
        HttpGet httpGet = new HttpGet(url);

        //设置请求信息
        httpGet.setConfig(this.getConfig());

        CloseableHttpResponse response = null;

        try {
            //3.使用HttpClient发起请求，获取response
            response = httpClient.execute(httpGet);

            //4.解析响应
            if (response.getStatusLine().getStatusCode() == 200) {
                //判断响应体Entity是否不为空，如果不为空就可以使用EntityUtils
                if(response.getEntity() != null){
                    String content = EntityUtils.toString(response.getEntity(), "utf8");
                    return content;
                }
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            //5.关闭response
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //6.不能关闭httpClient，由连接池管理httpClient
        }
        //没有数据
        return "";
    }

    private RequestConfig getConfig() {

        //HttpHost proxy = new HttpHost("192.168.1.101",8080,"http");

        //配置请求信息
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(1000)  //创建连接的最长时间，单位毫秒
                .setConnectionRequestTimeout(500)  //设置获取连接的最长时间，单位是毫秒
                .setSocketTimeout(10*1000)   //设置数据传输的最长时间
                //可以继续设置代理等配置信息
                //.setProxy(proxy)
                .build();
        return config;
    }

    public String doGetPic(String url){
        //1.不是每次创建新的HttpClient,而是从连接池中获取HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(this.cm).build();
        //2.创建HttpGet对象，设置url访问地址
        HttpGet httpGet = new HttpGet(url);

        //设置请求信息
        httpGet.setConfig(this.getConfig());

        CloseableHttpResponse response = null;

        try {
            //3.使用HttpClient发起请求，获取response
            response = httpClient.execute(httpGet);

            //4.解析响应
            if (response.getStatusLine().getStatusCode() == 200) {

                //判断响应体Entity是否不为空，
                if(response.getEntity() != null){

                    //获取图片后缀
                    String extName = url.substring(url.lastIndexOf("."));
                    //创建图片重命名
                    String picName = UUID.randomUUID().toString() + extName;
                    //下载图片,声明OutPutStream
                    OutputStream outputStream = new FileOutputStream(new File("D:\\pic\\"+picName));

                    response.getEntity().writeTo(outputStream);

                    //返回图片名称
                    return picName;
                }
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            //5.关闭response
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //6.不能关闭httpClient，由连接池管理httpClient
        }
        //下载失败或者没有数据
        return "";
    }
}
